//
//  HomeViewController.m
//  ATMCash
//
//  Created by zhengchengfeng on 2024/9/3.
//

#import "HomeViewController.h"
#import "AppDelegate.h"

#import "EmptyOrderTableCell.h"


#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>

#import "BannerView.h"

#import "HomeRepayTableViewCell.h"
#import "HomeProListTableViewCell.h"

#import "QualificationIntroController.h"
#import "OrderDetailViewController.h"
#import "ApplyProductViewController.h"

#import <CoreLocation/CoreLocation.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <CoreTelephony/CTCarrier.h>
#import <SystemConfiguration/SCNetworkReachability.h>
#import <Foundation/NSTimeZone.h>
#import <sys/types.h>
#import <sys/sysctl.h>
#import <mach/mach.h>
#import <net/if.h>
#import <net/if_dl.h>






//no network
static NSString * notReachable = @"notReachable";

#define kRepayCell      @"kRepayCell"
#define kListCell       @"kListCell"

#define kErrorCell      @"kErrorCell"

@interface HomeViewController ()<BannerViewDelegate>

@property (nonatomic) BOOL isNetworkError;

@property (nonatomic) HomeModel *mm;
@property (nonatomic) VictoryHomeCardModel *cardModel;

@property (nonatomic) NSMutableArray *bannerAry;

@property (nonatomic) BOOL isOffsetY;

@property (nonatomic) UIImageView *headBgImg;


@property (nonatomic) UIImageView *imgView;
@property (nonatomic) UILabel *topLab,*priceLab,*loanTermLab,*rateLab;
@property (nonatomic) UIButton *applyBtn;
@property (nonatomic) UIImageView *bottomImgView;


@property (nonatomic) NSInteger recorNoNetworkTimes;

@property (nonatomic) NSString *recordLastLoginTime;


@end

@implementation HomeViewController

- (NSMutableArray *)bannerAry{
    if (!_bannerAry) {
        _bannerAry = [[NSMutableArray alloc] init];
    }
    return _bannerAry;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
        
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        
        if (status == 1 || status == 2){
            self.isNetworkError = NO;
            if (self.recorNoNetworkTimes == 1) {
                [self loadData];
            }
            
            self.recorNoNetworkTimes = 0;
        }
        else{
            self.isNetworkError = YES;
            self.recorNoNetworkTimes = 1;
            self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
            [self.data removeAllObjects];
            DLog(@"============AFNetworkReachabilityStatusNotReachable========");
        }
        [self.tableView reloadData];
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    
    
    if (!self.isNetworkError) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self isOpenIdfa];
        });
    }
    
    [self loadData];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)isOpenIdfa{

    if (@available(iOS 14,*)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
        
            NSString *idfaStr = @"";
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
               
                idfaStr = [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
                DLog(@"==idfaStr==%@",idfaStr);
                
            } else {
                DLog(@"do not open idfa");
            }
            [self uploadIdfaData:idfaStr];
            
            [[NSUserDefaults standardUserDefaults] setValue:esString(idfaStr) forKey:kIDFAStr];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            DLog(@"--idfv---%@\n--idfa--%@",[UIDevice currentDevice].identifierForVendor.UUIDString,idfaStr);
        }];
    } else {
    
        NSString *idfaStr = @"";
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            idfaStr = [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
            DLog(@"==idfaStr==%@",idfaStr);
        }
        else {
            DLog(@"do not open idfa");
        }
        [[NSUserDefaults standardUserDefaults] setValue:esString(idfaStr) forKey:kIDFAStr];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [self uploadIdfaData:idfaStr];
        
        
        DLog(@"--idfv---%@\n--idfa--%@",[UIDevice currentDevice].identifierForVendor.UUIDString,idfaStr);
    }
    
    
    
}

- (void)uploadIdfaData:(NSString *)idfaStr{
    
    if (!self.isNetworkError) {
        if (![[NSUserDefaults standardUserDefaults] boolForKey:kHomeIDFA]) {
           
            NSMutableDictionary *muDic = @{
                @"eighteen":@"eighteenGoogle",
                @"devil":esString([UIDevice currentDevice].identifierForVendor.UUIDString),
                @"hit":esString(idfaStr),
            }.mutableCopy;
            [BaseDataEngine apiForPath:kUploadGoogleUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
                if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
                    return;
                }
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kHomeIDFA];
                [[NSUserDefaults standardUserDefaults] synchronize];
            } onCompleteFailur:^(NSError *error) {
                
            } withIsForm:YES];
            
        }
        
    }
    
    
}

- (void)viewDidLoad {
    self.isTableViewStyleGrouped = YES;
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"home";

    self.view.backgroundColor = self.tableView.backgroundColor = RGB(4, 44, 8);
    
    self.recordLastLoginTime = esString([[NSUserDefaults standardUserDefaults] valueForKey:kRecordLastTime]);
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kRecordLastTime];
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"] forKey:kRecordLastTime];
    
    [self.tableView registerClass:[HomeRepayTableViewCell class] forCellReuseIdentifier:kRepayCell];
    [self.tableView registerClass:[HomeProListTableViewCell class] forCellReuseIdentifier:kListCell];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:kNotificationMsg_Land_Sucess object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeNoti) name:kNotificationMsg_Exit_Success object:nil];
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kGeneralHeight)];
    [self.tableView registerClass:[EmptyHomeTableCell class] forCellReuseIdentifier:kErrorCell];
    
    
}


#pragma ----initHeadView
- (void)initHeadView{
    
    CGFloat headIMgHeight = DimensionBaseIphone6(540);
    
    UIImage *imgB = [UIImage imageNamed:@"icon_homeBgV"];
    
    if (self.bannerAry.count == 0) {
        imgB = [UIImage imageNamed:@"icon_homeBgV2"];
        headIMgHeight = DimensionBaseIphone6(423);
    }
    
    UIImage *applyImg = [UIImage imageNamed:@"icon_takeNow"];
    
    UIImage *imgQua = [UIImage imageNamed:@"icon_homeQua"];
   
    CGFloat kCardHeight = 0;
   
    if ([self.mm.ancestress.risen isEqualToString:kMakemoneyb] ) {
        kCardHeight += DimensionBaseIphone6(20) + DimensionBaseIphone6(imgQua.size.height) + DimensionBaseIphone6(12);
    }
    else{
        kCardHeight += DimensionBaseIphone6(20);
    }
    
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, headIMgHeight + kCardHeight)];
    headView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = headView;
    
    UIImageView *headBgImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, headView.frame.size.height - kCardHeight)];
    headBgImg.image = imgB;
    [headView addSubview:headBgImg];
    self.headBgImg = headBgImg;
    
    UIImage *img1 = [UIImage imageNamed:@"icon_homeTop"];
    UIButton *titleBtn = [[UIButton alloc] init];
    [headView addSubview:titleBtn];
    titleBtn.frame = CGRectMake((headView.width - img1.size.width)/2, DimensionBaseIphone6(49), img1.size.width, DimensionBaseIphone6(img1.size.height));
    [titleBtn setImage:img1 forState:UIControlStateNormal];
    
#pragma mark ----banner
    UIImage *imgBanner = [UIImage imageNamed:@"icon_homeTp"];
    BannerView *bannerView = [[BannerView alloc] initWithFrame:CGRectMake(15,titleBtn.bottom + DimensionBaseIphone6(10), kScreenWidth - 30, self.bannerAry.count == 0 ? 0:DimensionBaseIphone6(imgBanner.size.height))];
    bannerView.backgroundColor = [UIColor clearColor];
    bannerView.delegate = self;
    bannerView.bannerList = self.bannerAry;
    [headView addSubview:bannerView];
    
    
    
#pragma mark ----card
    UIImage *imgCard = [UIImage imageNamed:@"icon_homeBg"];
    
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, bannerView.bottom + DimensionBaseIphone6(10), kScreenWidth - 30, DimensionBaseIphone6(imgCard.size.height))];
    self.imgView.backgroundColor = [UIColor clearColor];
    self.imgView.image = [UIImage imageNamed:@"icon_homeBg"];
    [headView addSubview:self.imgView];
    
    self.imgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap0 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickApply)];
    [self.imgView addGestureRecognizer:tap0];
    
    self.topLab = [Utility createLabel:[UIFont fontWithName:kFutura size:12] color:[UIColor whiteColor]];
    [self.imgView addSubview:self.topLab];
    self.topLab.textAlignment = 1;
    self.topLab.frame = CGRectMake(0, DimensionBaseIphone6(90), self.imgView.size.width, DimensionBaseIphone6(20));
    
    self.priceLab = [Utility createLabel:[UIFont fontWithName:kFuturaBold size:44] color:[UIColor colorWithHexString:@"#FFEFC0"]];
    [self.imgView addSubview:self.priceLab];
    self.priceLab.textAlignment = 1;
    self.priceLab.frame = CGRectMake(0, self.topLab.bottom + DimensionBaseIphone6(20), self.imgView.size.width, DimensionBaseIphone6(60));
    
    self.loanTermLab = [Utility createLabel:[UIFont fontWithName:kFuturaMedium size:13] color:[UIColor colorWithHexString:@"#D9E4CE"]];
    [self.imgView addSubview:self.loanTermLab];
    self.loanTermLab.frame = CGRectMake(0, self.priceLab.bottom, self.imgView.size.width/2, DimensionBaseIphone6(45));
    
    self.loanTermLab.textAlignment = 1;
    self.loanTermLab.numberOfLines = 2;
    
    self.rateLab = [Utility createLabel:[UIFont fontWithName:kFuturaMedium size:13] color:[UIColor colorWithHexString:@"#D9E4CE"]];
    [self.imgView addSubview:self.rateLab];
    self.rateLab.frame = CGRectMake(self.loanTermLab.right, self.loanTermLab.top, self.imgView.size.width/2, DimensionBaseIphone6(45));
    self.rateLab.textAlignment = 1;
    self.rateLab.numberOfLines = 2;
    
    

    self.applyBtn = [[UIButton alloc] init];
    [headView addSubview:self.applyBtn];
    self.applyBtn.frame = CGRectMake((kScreenWidth - applyImg.size.width)/2, headBgImg.frame.size.height - DimensionBaseIphone6(45), applyImg.size.width, DimensionBaseIphone6(applyImg.size.height));
    [self.applyBtn setImage:applyImg forState:UIControlStateNormal];
    [self.applyBtn setImage:applyImg forState:UIControlStateHighlighted];
    [self.applyBtn setImage:applyImg forState:UIControlStateSelected];
    [self.applyBtn addTarget:self action:@selector(clickApply) forControlEvents:UIControlEventTouchUpInside];
    
#pragma mark ---qualification intro
    
    self.bottomImgView = [[UIImageView alloc] init];
    
    self.bottomImgView.backgroundColor = [UIColor clearColor];
//    self.bottomImgView.frame = CGRectMake((headView.frame.size.width - imgQua.size.width)/2, self.applyBtn.bottom + DimensionBaseIphone6(10), imgQua.size.width, DimensionBaseIphone6(imgQua.size.height));
    self.bottomImgView.frame = CGRectMake(15, self.applyBtn.bottom + DimensionBaseIphone6(20), kScreenWidth - 30, DimensionBaseIphone6(imgQua.size.height));
    self.bottomImgView.image = imgQua;
    
    self.bottomImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    [self.bottomImgView addGestureRecognizer:tap];
    
    
    self.topLab.text = @"Maximum Amount";
    self.priceLab.text = [NSString stringWithFormat:@"%@",esString(self.cardModel.satisfy)];
    self.loanTermLab.text = [NSString stringWithFormat:@"%@\n%@ %@",esString(self.cardModel.purposes),esString(self.cardModel.suppressing),esString(self.cardModel.lowhight)];
    self.rateLab.text = [NSString stringWithFormat:@"%@\n%@ %@",esString(self.cardModel.talents),esString(self.cardModel.faithful),esString(self.cardModel.loanRateUnit)];

    [self.loanTermLab addAttributesArray:@[@{NSFontAttributeName:[UIFont fontWithName:kFuturaMedium size:18]},@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFEFC0"]},@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFEFC0"]}] forStringArray:@[esString(self.cardModel.suppressing),esString(self.cardModel.suppressing),esString(self.cardModel.lowhight)]];
    
    [self.rateLab addAttributesArray:@[@{NSFontAttributeName:[UIFont fontWithName:kFuturaMedium size:18]},@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFEFC0"]},@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFEFC0"]}] forStringArray:@[esString(self.cardModel.faithful),esString(self.cardModel.faithful),esString(self.cardModel.loanRateUnit)]];
    
    
    
    
    if ([self.mm.ancestress.risen isEqualToString:kMakemoneyb] ) {
        self.bottomImgView.hidden = NO;
       
        [headView addSubview:self.bottomImgView];
    }
    else{
        self.bottomImgView.hidden = YES;
    }
    
}

- (void)bannerView:(BannerView *)bannerView openUrlPath:(NSString *)urlPath{
    
    DLog(@"====%@",urlPath);
    
   
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:kIsNeedLocation] integerValue] == 1) {
      
        if (![StringUtil determineWhetherTheAPPOpensTheLocation]) {
            return;
        }
        
    }
    
    if (![[CurrentUser mine] hasLogged]) {
        [CreaditUtilsHelper actionWhenLogin:^{
            
        } onVC:self];
    } else {
        [[CreditCore globleCore] jumpToPage:esString(urlPath)];
    }
    
    
    
}

- (void)clickApply{
    
    [self enterOrderDetail:esString(self.cardModel.girded)];
    
}

- (void)tap{
    
    QualificationIntroController *vc = [[QualificationIntroController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)removeNoti{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)loadData{
    
    if (self.isNetworkError) {
        return;
    }
    
    NSMutableDictionary *muDic = @{
        @"dropped":@"homeDropped",
        @"clergyman":@"homeClergyman",
    }.mutableCopy;
    [CreaditUtilsHelper boxShowLoadWithMessage:@"" onView:self.view withOffsetHeight:0];
    [BaseDataEngine apiForPath:kHomeUrl method:kGetMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        [CreaditUtilsHelper hideLoadMessageBox];
        [CreaditUtilsHelper hideLoadMessageBoxFromView:self.view];
        
        DLog(@"=====%@",responseDic);
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }
        
        NSDictionary *dic = responseDic[@"recollecting"];
        

        HomeModel *mm = [HomeModel mj_objectWithKeyValues:dic];
        self.mm = mm;
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kIsNeedLocation];
        [[NSUserDefaults standardUserDefaults] setValue:esString(self.mm.egoism) forKey:kIsNeedLocation];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [self.data removeAllObjects];
        [self.bannerAry removeAllObjects];
        
        if ([self.mm.entangling.risen isEqualToString:kMakemoneya]) {
            if (self.mm.entangling.victory.count > 0) {
                [self.bannerAry addObjectsFromArray:self.mm.entangling.victory];
            }
        }
        
        if ([self.mm.ancestress.risen isEqualToString:kMakemoneyb] || [self.mm.ancestress.risen isEqualToString:kMakemoneyc]) {
            if (self.mm.ancestress.victory.count > 0) {
                self.cardModel = [VictoryHomeCardModel mj_objectWithKeyValues:self.mm.ancestress.victory.firstObject];
            }
        }

        NSDictionary *dic1 = @{
                               @"title" : @"",
                               @"selSec" : @"",
                               @"class" : [HomeRepayTableViewCell class],
                               @"value" : self.mm.entrusted.victory.count ? self.mm.entrusted.victory : @"",
                               @"sel" : @"",
                               };
        
        NSDictionary *dic2 = @{
                               @"title" : @"",
                               @"selSec" : @"",
                               @"class" : [HomeProListTableViewCell class],
                               @"value" : self.mm.healing.victory.count ? self.mm.healing.victory : @"",
                               @"sel" : @"",
                               };
        
       
        if ([self.mm.entrusted.risen isEqualToString:kMakemoneyd]) {
            [self.data addObject:dic1];
        }
       
        if ([self.mm.healing.risen isEqualToString:kMakemoneye]) {
            [self.data addObject:dic2];
        }
                
        [self initHeadView];
        [self.tableView reloadData];
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBox];
        [CreaditUtilsHelper hideLoadMessageBoxFromView:self.view];
    } withIsForm:NO];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.isNetworkError) {
        return 1;
    }
    return self.data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isNetworkError) {
        return 1;
    }
    /*
    id value = [self.data[section] valueForKey:@"value"];
    NSDictionary * dataDictionary = self.data[section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeProListTableViewCell class]){
        if (isArray(value)) {
            NSArray * datas = (NSArray *)value;
            return datas.count;
        }
        else{
            return 0;
        }
    }
     */
    return 1;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isNetworkError) {
        return kScreenHeight;
    }
    
    if (self.data.count == 0) {
        return 0.0001f;
    }
    
    NSDictionary * dataDictionary = self.data[indexPath.section];
    Class cellClass = dataDictionary[@"class"];
    
    if (cellClass == [HomeRepayTableViewCell class]){
        return 90;
    }
    else if (cellClass == [HomeProListTableViewCell class]){
        /*
        return 136;
         */
        if (self.mm.healing.victory.count > 0) {
          
            if (self.mm.healing.victory.count <= 3) {
                return 38 + 136*3 + 25;
            }
            return 38 + 136*self.mm.healing.victory.count + 25;
            
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.isNetworkError) {
        EmptyHomeTableCell *cell = [tableView dequeueReusableCellWithIdentifier:kErrorCell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isErrorData = YES;
        cell.clickBtnBlock = ^{
            TipsAlertView *alertV = [[TipsAlertView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:@"To use Mabilis Money,you must enable network permission to use the App functions normally." withCancelStr:@"Stop" withSureStr:@"Turning On"];
            
            UIWindow *window =  [UIApplication sharedApplication].keyWindow;
            if (@available(iOS 14,*)) {
                window =  [[[UIApplication sharedApplication] windows] objectAtIndex:0];
            }
            [window addSubview:alertV];
            
            alertV.clickSureBlock = ^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {
                                    
                }];
            };
        };
        return cell;
    }
    
    NSDictionary * dataDictionary = self.data[indexPath.section];
    Class cellClass = dataDictionary[@"class"];
    
    if (cellClass == [HomeRepayTableViewCell class]){
        return [self getRepayIndexPath:indexPath];
    }
    else if (cellClass == [HomeProListTableViewCell class]){
        return [self getListIndexPath:indexPath];
    }
    return nil;
}


- (UITableViewCell *)getRepayIndexPath:(NSIndexPath *)indexPath{
    HomeRepayTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kRepayCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *ary = [self.data[indexPath.section] valueForKey:@"value"];
    if (isArray(ary)) {
        [cell reloadData:ary];
        cell.callBackBannerReplyBlock = ^(NSString * _Nonnull urlStr) {
            DLog(@"===========%@",urlStr);
            if ([[[NSUserDefaults standardUserDefaults] valueForKey:kIsNeedLocation] integerValue] == 1) {
                if (![StringUtil determineWhetherTheAPPOpensTheLocation]) {
                    return;
                }
            }
            
            if (![[CurrentUser mine] hasLogged]) {
                [CreaditUtilsHelper actionWhenLogin:^{
                    
                } onVC:self];
            } else {
                [[CreditCore globleCore] jumpToPage:esString(urlStr)];
            }
            
            
        };
    }
    return cell;
}

- (UITableViewCell *)getListIndexPath:(NSIndexPath *)indexPath{
    HomeProListTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kListCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    /*
    NSArray *ary = [HomeProductListModel mj_objectArrayWithKeyValuesArray:[self.data[indexPath.section] valueForKey:@"value"]];
    if (isArray(ary)) {
        cell.listM = ary[indexPath.row];
    }
     */
    if (self.mm.healing.victory.count > 0) {
        [cell reloadData:self.mm.healing.victory];
        cell.callBackOrderIdStr = ^(NSString * _Nonnull idStr) {
            DLog(@"-----------%@",idStr);
            [self enterOrderDetail:idStr];
        };
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.isNetworkError) {
        return;
    }
    /*
    NSDictionary * dataDictionary = self.data[indexPath.section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeProListTableViewCell class]){
        NSArray *ary = [HomeProductListModel mj_objectArrayWithKeyValuesArray:[self.data[indexPath.section] valueForKey:@"value"]];
        if (isArray(ary)) {
            HomeProductListModel *model = ary[indexPath.row];
            DLog(@"-----%@",model.productName);
            [self enterOrderDetail:esString(model.girded)];
        }
    }
     */
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *secHeaderView = [[UIView alloc] init];
    if (self.isNetworkError) {
        return secHeaderView;
    }
    /*
    NSDictionary * dataDictionary = self.data[section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeProListTableViewCell class]){

        UIImageView *imgV = [[UIImageView alloc] init];
        imgV.backgroundColor = [UIColor clearColor];
        imgV.image = [UIImage imageNamed:@"icon_home1"];
        [secHeaderView addSubview:imgV];
        imgV.frame = CGRectMake(15, 0, kScreenWidth - 30, 50);

        UIImage *ic2 = [UIImage imageNamed:@"icon_homeMore"];
        UIImageView *bgimg = [[UIImageView alloc] init];
        [imgV addSubview:bgimg];
        bgimg.image = ic2;
        bgimg.frame = CGRectMake((imgV.size.width - ic2.size.width)/2, (imgV.size.height - ic2.size.height)/2, ic2.size.width, ic2.size.height);

    }
    */
    return secHeaderView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.isNetworkError) {
        return 0.0001f;
    }
    /*
    NSDictionary * dataDictionary = self.data[section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeProListTableViewCell class]){
        return 50;
    }
     */
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *secFooterView = [[UIView alloc] init];
    secFooterView.backgroundColor = [UIColor clearColor];
    
    if (self.data.count == 0) {
        return secFooterView;
    }
    /*
    NSDictionary * dataDictionary = self.data[section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeProListTableViewCell class]){

        UIImage *ic = [UIImage imageNamed:@"icon_home3"];
        UIImageView *imgV = [[UIImageView alloc] init];
        imgV.backgroundColor = [UIColor clearColor];
        imgV.image = ic;
        [secFooterView addSubview:imgV];
        imgV.frame = CGRectMake(15, 0, kScreenWidth - 30, ic.size.height);

    }
     */
    
    return secFooterView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.isNetworkError) {
        return 0.0001f;
    }
    
    /*
    NSDictionary * dataDictionary = self.data[section];
    Class cellClass = dataDictionary[@"class"];
    if (cellClass == [HomeProListTableViewCell class]){
        UIImage *ic = [UIImage imageNamed:@"icon_home3"];
        return ic.size.height;
    }
     */
    
    return 15.0001f;
}

#pragma mark ---uploadLocationData
- (void)uploadLocationData{
    if (![StringUtil determineWhetherTheAPPOpensTheLocation]) {
        return;
    }
    NSString *longitude =    [[NSUserDefaults standardUserDefaults] valueForKey:kLongitude];
    NSString *latitude =     [[NSUserDefaults standardUserDefaults] valueForKey:kLatitude];
    NSString *eatStr =       [[NSUserDefaults standardUserDefaults] valueForKey:kEatStr];
    NSString *officersStr =  [[NSUserDefaults standardUserDefaults] valueForKey:kOfficersStr];
    NSString *soldiersStr =  [[NSUserDefaults standardUserDefaults] valueForKey:kSoldiersStr];
    NSString *earningStr =   [[NSUserDefaults standardUserDefaults] valueForKey:kEarningStr];
    NSString *starvedStr =   [[NSUserDefaults standardUserDefaults] valueForKey:kStarvedStr];
    
    NSMutableDictionary *muDic = @{
        @"eat":     PMStringIsEmpty(eatStr)      ? @"":esString(eatStr),
        @"officers":PMStringIsEmpty(officersStr) ? @"":esString(officersStr),
        @"soldiers":PMStringIsEmpty(soldiersStr) ? @"": esString(soldiersStr),
        @"earning": PMStringIsEmpty(earningStr)  ? @"":esString(earningStr),
        @"starved": PMStringIsEmpty(starvedStr)  ? @"":esString(starvedStr),
        @"army":    PMStringIsEmpty(latitude)    ? @"":latitude,
        @"sore":    PMStringIsEmpty(longitude)   ? @"":longitude,
        @"engineer":@"engineerLocation",
        @"shillings":@"shillingsLocation",
    }.mutableCopy;
    [BaseDataEngine apiForPath:kUploadLocationUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            return;
        }
        DLog(@"---- upload location success ---");
    } onCompleteFailur:^(NSError *error) {
        
    } withIsForm:YES];
}

#pragma mark ---enterOrderDetail
- (void)enterOrderDetail:(NSString *)idStr{
    
    
    
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [[CreditCore globleCore] initLocationJudge];
        return;
    }
    
    [[CreditCore globleCore] initLocationJudge]; 
    
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:kIsNeedLocation] integerValue] == 1) {
        if (![StringUtil determineWhetherTheAPPOpensTheLocation]) {
            return;
        }
    }
    
    
    if (![[CurrentUser mine] hasLogged]) {
        [CreaditUtilsHelper actionWhenLogin:^{
            
        } onVC:self];
    }
    else {
        
        [self uploadLocationData];
        [self uploadDeviceData];
    
        [CreaditUtilsHelper boxShowLoadWithMessage:@""];
        NSMutableDictionary *muDic = @{
            @"gardens":esString(idStr),
            @"windows":@"windowsChoose",
            @"broken":@"brokenChoose",
        }.mutableCopy;
        [BaseDataEngine apiForPath:kApplyProUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
            DLog(@"-----%@",responseDic);
            [CreaditUtilsHelper hideLoadMessageBox];
            if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
                [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
                return;
            }
            NSDictionary *dic = responseDic[@"recollecting"];
            
            if (!PMStringIsEmpty(dic[@"exulting"])) {

                [[CreditCore globleCore] jumpToPage:esString(dic[@"exulting"])];

            }
            else {
                OrderDetailViewController *vc = [[OrderDetailViewController alloc] init];
                vc.orderIdStr = esString(idStr);
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
           
            
        } onCompleteFailur:^(NSError *error) {
            [CreaditUtilsHelper hideLoadMessageBox];
        } withIsForm:YES];
        
    }

    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.isNetworkError) {
        return;
    } 
    CGFloat offset_Y = scrollView.contentOffset.y;
   
    if (offset_Y < 0) {
        if (offset_Y < - kNavigationBarHeight) {
            self.isOffsetY = YES;
        }
    }
    else{
        if (self.isOffsetY) {
            self.isOffsetY = NO;
            [self loadData];
        }
    }
}

#pragma mark ---uploadDeviceData
- (void)uploadDeviceData{
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    NSString *idfaStr = [[NSUserDefaults standardUserDefaults] valueForKey:kIDFAStr];
    NSMutableDictionary *muDic = @{
        @"relit":@"ios",
        @"ashes":[UIDevice currentDevice].systemVersion,
        @"knocked":esString(self.recordLastLoginTime),
        @"energy":kAppBundleId,
        @"privation":@{
            @"millions":@"",
            @"chicago":@"",
            @"condemns":@"iPhone",
            @"wheat":[NSString stringWithFormat:@"%.1lf",kScreenHeight],
            @"individual":[UIDevice currentDevice].name,
            @"agriculture":[NSString stringWithFormat:@"%.1lf",kScreenWidth],
            @"boardredred":[UIDevice currentDevice].model,
            @"dalroy":[NSString stringWithFormat:@"%.1lf",[self getDeviceSize]],
            @"needed":[UIDevice currentDevice].systemVersion,
        },
        
        @"wants":@{
            @"hounded":[NSString stringWithFormat:@"%.1lf%@",[UIDevice currentDevice].batteryLevel*100,@"%"],
            @"hampering":[UIDevice currentDevice].batteryState == UIDeviceBatteryStateCharging ? @"1":@"0",
        },
        @"soiled":@{
            @"devil":esString([UIDevice currentDevice].identifierForVendor.UUIDString),//idfv
            @"hit":PMStringIsEmpty(idfaStr) ? @"" : idfaStr,
            @"money":[NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"],
            @"healthy":[self isOpenProxy] ? @"1":@"0",
            @"mines":[self isOpenVPN] ? @"1":@"0",
            @"twelve":[self isYY] ? @"1":@"0",
            @"is_simulator":[self isSimulator] ? @"1":@"0",
            @"thirteen":[self getDeviceLanguage],
            @"farm":[self getNetworkType],
            @"upset":[NSTimeZone localTimeZone].name,
            @"earned":[self getOperatorName],
            @"husband":[[NSUserDefaults standardUserDefaults] valueForKey:kAppLaunchTime],
            @"penny":[self getMacAddress],
        },
        
        
        @"miracle":@{
            @"basketsful": [self getIPAddress],
            @"fragments":@[
                @{
                    @"cambridge":@"",
                    @"feed":@"",
                    @"penny":@"",
                    @"managed":@"",
                },
            ],
            @"chief":@{
                @"cambridge":PMStringIsEmpty([[self getWIFIDict] valueForKey:@"SSID"]) ? @"":[[self getWIFIDict] valueForKey:@"SSID"],
                @"feed":PMStringIsEmpty([[self getWIFIDict] valueForKey:@"BSSID"]) ? @"":[[self getWIFIDict] valueForKey:@"SSID"],
                @"penny":@"",
                @"managed":PMStringIsEmpty([[self getWIFIDict] valueForKey:@"SSID"]) ? @"":[[self getWIFIDict] valueForKey:@"SSID"],
            },
            @"headed":@"0",
        },
        @"ghastly":@{
            @"makes":[NSString stringWithFormat:@"%.1lf",[self getUseStoreMemory]],
            @"cheap":[NSString stringWithFormat:@"%.1lf",[self getAllStoreMemory]],
            @"cost":[self getTotalMemory],
            @"railway":[NSString stringWithFormat:@"%.1lf",[self availableMemory]],
        },
        
        
    }.mutableCopy;
    DLog(@"------%@",muDic);
    
    
    NSMutableDictionary *upDic = @{
        @"recollecting":[NSString dictionaryToJson:muDic],
    }.mutableCopy;

    [BaseDataEngine apiForPath:kUploadDeviceInfoUrl method:kPostMethod parameter:upDic onCompleteSuccess:^(NSDictionary *responseDic) {
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            return;
        }
        DLog(@"---- upload device success ---");
    } onCompleteFailur:^(NSError *error) {
        
    } withIsForm:YES];
}

- (CGFloat)getAllStoreMemory{
    NSFileManager *fileManager = [NSFileManager defaultManager];
     
    
    NSNumber *fileSystemSize = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil][NSFileSystemSize];
    unsigned long long totalSize = [fileSystemSize unsignedLongLongValue];
     
    
    NSNumber *freeFileSystemSize = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil][NSFileSystemFreeSize];
    unsigned long long freeSize = [freeFileSystemSize unsignedLongLongValue];
     
   
    DLog(@"Total Size: %llu GB", totalSize / 1024 / 1024 / 1024);
    return totalSize;

}
- (CGFloat)getUseStoreMemory{
    NSFileManager *fileManager = [NSFileManager defaultManager];
     
    NSNumber *fileSystemSize = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil][NSFileSystemSize];
    unsigned long long totalSize = [fileSystemSize unsignedLongLongValue];
     
    NSNumber *freeFileSystemSize = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil][NSFileSystemFreeSize];
    unsigned long long freeSize = [freeFileSystemSize unsignedLongLongValue];
    
    DLog(@"Free Size: %llu GB", freeSize / 1024 / 1024 / 1024);
    return freeSize;

}
 
- (NSString *)getTotalMemory {
   
    int mib[2] = {CTL_HW, HW_MEMSIZE};
    uint64_t mem;
    size_t mem_size = sizeof(mem);
 
    
    if (sysctl(mib, 2, &mem, &mem_size, NULL, 0) == -1) {
        NSLog(@"Error getting memory size");
        return @"0";
    }
 
    unsigned long long result = mem;
    NSString *memorySize;
    
    if (result >= (1024ULL * 1024ULL * 1024ULL)) {
        memorySize = [NSString stringWithFormat:@"%.1f", ((double)result)];
    } else if (result >= (1024ULL * 1024ULL)) {
        memorySize = [NSString stringWithFormat:@"%.1f", ((double)result)];
    } else if (result >= 1024ULL) {
        memorySize = [NSString stringWithFormat:@"%.1f", ((double)result)];
    } else {
        memorySize = [NSString stringWithFormat:@"%llu", result];
    }
 
    return memorySize;
}

- (double)availableMemory{
  vm_statistics_data_t vmStats;
  mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
  kern_return_t kernReturn = host_statistics(mach_host_self(),
                                             HOST_VM_INFO,
                                             (host_info_t)&vmStats,
                                             &infoCount);
  
  if (kernReturn != KERN_SUCCESS) {
    return NSNotFound;
  }
    return vm_page_size *vmStats.free_count;
//  return ((vm_page_size *vmStats.free_count) / 1024.0) / 1024.0;
}


- (NSString *)getOperatorName{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = nil;
    NSString *radioType = nil;
    
    if (info && [info respondsToSelector:@selector(serviceSubscriberCellularProviders)]) {
        NSDictionary *dic = [info serviceSubscriberCellularProviders];
        if (dic.allKeys.count) {
            carrier = [dic objectForKey:dic.allKeys[0]];
        }
    }
    
    if (info && [info respondsToSelector:@selector(serviceCurrentRadioAccessTechnology)]) {
        NSDictionary *radioDic = [info serviceCurrentRadioAccessTechnology];
        if (radioDic.allKeys.count) {
            radioType = [radioDic objectForKey:radioDic.allKeys[0]];
        }
    }
    return PMStringIsEmpty(carrier.carrierName) ? @"":esString(carrier.carrierName);
}

- (NSString *)getNetworkType{
    
    struct sockaddr_storage zeroAddress;
    
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.ss_len = sizeof(zeroAddress);
    zeroAddress.ss_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    
    if (!didRetrieveFlags) {
        return notReachable;
    }
    
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    if (isReachable && !needsConnection) { }else{
        return notReachable;
    }
    
    
    if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == kSCNetworkReachabilityFlagsConnectionRequired ) {
        
        return notReachable;
        
    } else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
        
        return [self cellularType];
        
    } else {
        return @"WiFi";
    }
    
}

- (NSString *)cellularType{
    
    CTTelephonyNetworkInfo * info = [[CTTelephonyNetworkInfo alloc] init];
    
    NSString *currentRadioAccessTechnology;
    if (@available(iOS 12.1, *)) {
        if (info && [info respondsToSelector:@selector(serviceCurrentRadioAccessTechnology)]) {
            NSDictionary *radioDic = [info serviceCurrentRadioAccessTechnology];
            if (radioDic.allKeys.count) {
                currentRadioAccessTechnology = [radioDic objectForKey:radioDic.allKeys[0]];
            } else {
                return notReachable;
            }
        } else {
            
            return notReachable;
        }
        
    } else {
        
        currentRadioAccessTechnology = info.currentRadioAccessTechnology;
    }
    
    if (currentRadioAccessTechnology) {
        
        if (@available(iOS 14.1, *)) {
            
            if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyNRNSA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyNR]) {
                
                return @"5G";
                
            }
        }
        
        if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
            
            return @"4G";
            
        } else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyWCDMA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSDPA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSUPA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD]) {
            
            return @"3G";
            
        } else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
            
            return @"2G";
            
        } else {
            
            return @"Unknow";
        }
        
    } else {
        return notReachable;
    }
}




- (BOOL)isYY{
    BOOL status = NO;
    status = [[NSFileManager defaultManager] fileExistsAtPath:@"User/Applications"];
    if (status) {
        return YES;
    }
    return NO;
}

- (BOOL)isOpenProxy{
    NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
    NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"https://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
    NSDictionary *settings = proxies[0];
    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]) {
        return NO;
    }
    return YES;
    
}

- (BOOL)isOpenVPN{
    BOOL flag = NO;
    NSDictionary *dict = CFBridgingRelease(CFNetworkCopySystemProxySettings());
    NSArray *keys = [dict[@"__SCOPED__"] allKeys];
    for (NSString *key in keys) {
        if ([key rangeOfString:@"tap"].location != NSNotFound ||
            [key rangeOfString:@"tun"].location != NSNotFound ||
            [key rangeOfString:@"ipsec"].location != NSNotFound ||
            [key rangeOfString:@"ppp"].location != NSNotFound){
            flag = YES;
            break;
            
        }
    }
    return flag;
}
 
- (BOOL)isSimulator {
    return TARGET_IPHONE_SIMULATOR;
}

- (NSString *)getIPAddress{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    success = getifaddrs(&interfaces);
    if (success == 0) {
       
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                   
                    struct sockaddr_in *sa = (struct sockaddr_in *)temp_addr->ifa_addr;
                    address = [NSString stringWithUTF8String:inet_ntoa(sa->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
   
    freeifaddrs(interfaces);
    return address;
}
 
- (CGFloat)getDeviceSize{
    CGSize devicePhysicalSize = [[UIScreen mainScreen] nativeBounds].size;
    CGFloat heightInInches = devicePhysicalSize.height / [[UIScreen mainScreen] nativeScale] / 160.0;
    return heightInInches;
}


- (NSString *)getDeviceLanguage {
    NSArray *languageArray = [NSLocale preferredLanguages];
    return [languageArray objectAtIndex:0];
}

- (NSString *)getMacAddress{
       
    int  temp[6]={0};
    size_t len=0;
    char *buf=NULL;
    unsigned char *laddr=NULL;
    struct if_msghdr *ifmsghdr=NULL;
    struct sockaddr_dl *sockaddr=NULL;
    
    temp[0] = CTL_NET;
    temp[1] = AF_ROUTE;
    temp[2] = 0;
    temp[3] = AF_LINK;
    temp[4] = NET_RT_IFLIST;
    
    temp[5] = if_nametoindex("en0");
    if (0 == temp[5])
    {
        return nil;
    }
    
    if (sysctl(temp, 6, NULL, &len, NULL, 0) < 0)
    {
        return nil;
    }
    
    buf = malloc(len+32);
    if (buf == NULL)
    {
        return nil;
    }
    
    if (sysctl(temp, 6, buf, &len, NULL, 0) < 0)
    {
        free(buf);
        
        return nil;
    }
    
    ifmsghdr = (struct if_msghdr *)buf;
    sockaddr = (struct sockaddr_dl *)(ifmsghdr + 1);
    laddr = (unsigned char *)LLADDR(sockaddr);
 
    NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *laddr, *(laddr+1), *(laddr+2), *(laddr+3), *(laddr+4), *(laddr+5)];
    free(buf);
    
    return [outstring uppercaseString];

    
    
}

- (NSDictionary *)getWIFIDict{

    NSArray *interfaces = (__bridge_transfer id)CNCopySupportedInterfaces();
    id info = nil;
    for (NSString *interfaceName in interfaces) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName);
        if (info && [info count]) {
            break;
        }
    }

    if (info) {
        NSDictionary *networkInfo = (NSDictionary *)info;
        NSString *SSID = [networkInfo valueForKey:@"SSID"];
        NSString *BSSID = [networkInfo valueForKey:@"BSSID"];
//        NSLog(@"WiFi Name: %@", [networkInfo objectForKey:(__bridge id)kCNNetworkInfoKeySSID]);
//        NSLog(@"WiFi BSSID: %@", [networkInfo objectForKey:(__bridge id)kCNNetworkInfoKeyBSSID]);
//        DLog(@"SSID: %@, BSSID: %@", SSID, BSSID);
        return networkInfo;
    } else {
        DLog(@"Not connected to WiFi");
    }

    
    
    

    return nil;

    
}

 

@end
